/*
 * @Author: Wangjun
 * @Date: 2022-07-13 13:33:24
 * @LastEditTime: 2024-04-01 13:30:05
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \libs\aescry\aes.go
 * hnxr
 */
package aescry

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha1"
	"encoding/hex"
	"strings"
)

func MakeKey(pass string, l ...int) (key string) {
	h := sha1.New()
	h.Write([]byte(pass))
	key = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
	size := 16 //16,24, 32
	if len(l) > 0 {
		size = l[0]
	}
	switch {
	case size >= 32:
		size = 32
	case size >= 24:
		size = 24
	default:
		size = 16
	}

	return key[:size]
}

func pkcsS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
func pcks5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

/**
 * @description: 加密
 * @param {*} origData
 * @param {[]byte} key
 * @return {*}
 */
func Encrypt(origData, pass []byte) ([]byte, error) {
	block, err := aes.NewCipher(pass)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = pkcsS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, pass[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

/**
 * @description: 解密
 * @param {*} crypted
 * @param {[]byte} key
 * @return {*}
 */
func Decrypt(crypted, pass []byte) ([]byte, error) {
	block, err := aes.NewCipher(pass)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, pass[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = pcks5UnPadding(origData)
	return origData, nil
}
